package com.zline.foodraise.view;

import android.content.Context;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.DynamicItemCommentItemAdapter;
import com.zline.foodraise.adapter.DynamicItemProPicturesItemAdapter;
import com.zline.foodraise.adapter.DynamicItemSupportItemAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.CommentBean;
import com.zline.foodraise.entity.CustomerUserBean;
import com.zline.foodraise.entity.MomentBean;
import com.zline.foodraise.entity.PictureBean;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.DynamicListener;
import com.zline.foodraise.listener.RecyclerItemClicked;
import com.zline.foodraise.util.ImageUtil;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.TimeUtil;

import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by heshantao on 15/7/6.
 * 动态列表Item
 */
@EViewGroup(R.layout.dynamic_item)
public class DynamicItem extends RelativeLayout {
    private static final String LOG_TAG = DynamicItem.class.getSimpleName();
    @ViewById(R.id.dynamic_item_pics_about_dynamic_recyclerView)
    RecyclerView propicture_list_recyclerview;
    @Bean
    DynamicItemProPicturesItemAdapter proPicturesItemAdapter;
    SparseArray<String> proPicturesArray;
    @ViewById(R.id.dynamic_item_support_list_recyclerView)
    RecyclerView support_list_recyclerview;
    @Bean
    DynamicItemSupportItemAdapter supportItemAdapter;
    SparseArray<CustomerUserBean> supportArray;
    @ViewById(R.id.dynamic_item_comment_list_recyclerView)
    RecyclerView comment_list_recyclerview;
    @Bean
    DynamicItemCommentItemAdapter commentItemAdapter;
    SparseArray<CommentBean> commentArray;
    Context cxt;
    RecyclerItemClicked itemClicked;
    DynamicListener dynamicListener;
    MomentBean momentBean;
    //发布评论者头像
    @ViewById(R.id.dynamic_item_person_icon_circleIv)
    CircleImageView person_civ;
    @ViewById(R.id.dynamic_item_vip)
    ImageView V_iv;
    //发布动态人姓名
    @ViewById(R.id.dynamic_item_person_name)
    TextView dynamic_person_name_tv;
    //动态发布时间
    @ViewById(R.id.dynamic_item_dynamic_published_time_tv)
    TextView dynamic_published_time_tv;
    //动态内容
    @ViewById(R.id.dynamic_item_dynamic_tv)
    TextView dynamic_content_tv;
    //赞TA 图标
    @ViewById(R.id.dynamic_item_support_iv)
    ImageView dynamic_support_iv;
    //赞的数量
    @ViewById(R.id.dynamic_item_support_num_tv)
    TextView dynamic_support_num_tv;
    //评论详情总数量
    @ViewById(R.id.dynamic_item_comment_detatil_tv)
    TextView dynamic_comment_detail_num_tv;
    //当动态只有一张图片时候
    @ViewById(R.id.dynamic_item_one_pic_iv)
    RoundedImageView dynamic_pic_iv;
    //评论说明信息
    @ViewById(R.id.dynamic_item_comment_detatil_rl)
    RelativeLayout comment_hint_rl;
    //赞信息列表
    @ViewById(R.id.dynamic_item_support_rl)
    RelativeLayout dynamic_item_support_rl;
    @Bean
    ImageUtil imageUtil;
    ImageLoader imageLoader;
    DisplayImageOptions options;
    int position;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    //动态ID
    long momentId;
    //赞的数量
    int support_num;
    //1代表赞过，0代表未赞过
    int is_support;
    @StringRes(R.string.today)
    String today;
    @Bean
    TimeUtil timeUtil;
    int authenticateType;

    public DynamicItem(Context context) {
        super(context);
        this.cxt = context;
    }

    public void bind(MomentBean momentBean, int position,DisplayImageOptions options) {
        this.momentBean = momentBean;
        this.position = position;
        this.options=options;
        initData();
        initView();
    }

    void initData() {
        //图片列表
        List<PictureBean> pictureBeanList = momentBean.getPictureBeanList();
        proPicturesArray = new SparseArray<String>();
        for (int i = 0; i < pictureBeanList.size(); i++) {
            proPicturesArray.put(i, pictureBeanList.get(i).getPictureUrl());
        }
        //赞列表
        List<CustomerUserBean> fnInMomentPraiseList = momentBean.getFnInMomentPraiseList();
        supportArray = new SparseArray<CustomerUserBean>();
        int praiseSize = fnInMomentPraiseList.size() > 6 ? 6 : fnInMomentPraiseList.size();
        for (int i = 0; i < praiseSize; i++) {
            supportArray.put(i, fnInMomentPraiseList.get(i));
        }

        //最新的3条评论列表
        List<CommentBean> fnInCommentBeanList = momentBean.getFnInCommentBeanList();
        commentArray = new SparseArray<CommentBean>();
        int size = fnInCommentBeanList.size() > 3 ? 3 : fnInCommentBeanList.size();
        for (int i = 0; i < size; i++) {
            commentArray.put(i, fnInCommentBeanList.get(i));
        }
    }

    void initView() {
        setRecyclerView();
        setOtherInfo();
    }


    //如果图片列表只有一张图片的话就不需要recyclerView 呈现
    void setRecyclerView() {
        if (proPicturesArray.size() == 1) {
            propicture_list_recyclerview.setVisibility(View.GONE);
            imageLoader = ImageLoader.getInstance();
            DisplayImageOptions options = imageUtil.
                    getDisplayImageOptions(R.mipmap.default_product_icon,
                            R.mipmap.default_product_icon, R.mipmap.default_product_icon);
            imageLoader.displayImage(proPicturesArray.get(0), dynamic_pic_iv, options);
            dynamic_pic_iv.setVisibility(View.VISIBLE);
        } else {
            dynamic_pic_iv.setVisibility(View.GONE);
            setProPicturesRecyclerView();
        }
        setSupportRecyclerView();
        setCommentRecyclerView();
    }

    //设置其他信息
    void setOtherInfo() {
        imageLoader = ImageLoader.getInstance();
        CustomerUserBean userBean = momentBean.getUserBean();
        if (userBean != null) {
            String picUrl = userBean.getAvatarPicUrl();
            authenticateType = userBean.getIdentificateType();
            if(authenticateType==1){
                V_iv.setVisibility(View.VISIBLE);
            }else{
                V_iv.setVisibility(View.GONE);
            }
            imageLoader.displayImage(picUrl, person_civ, options);
            String name = userBean.getNickName();
            dynamic_person_name_tv.setText(name);
        }
        long timeStamp = momentBean.getCreateTimeStamp();
        String createTime = formatData(timeStamp);
        dynamic_published_time_tv.setText(createTime);
        String content = momentBean.getContent();
        //最多3行超出部分省略号
        dynamic_content_tv.setMaxLines(3);
        dynamic_content_tv.setEllipsize(TextUtils.TruncateAt.END);
        dynamic_content_tv.setText(content);
        support_num = momentBean.getMomentPraiseCount();
        dynamic_support_num_tv.setText(support_num + "");
        //是否给该评论点过赞
        is_support = momentBean.getIsPraise();
        changSupportStatus(is_support);
        //如果没人点赞就不显示
        if (support_num == 0) {
            dynamic_item_support_rl.setVisibility(View.GONE);
        } else {
            dynamic_item_support_rl.setVisibility(View.VISIBLE);
        }

        int comment_num = momentBean.getCommentCount();
        String look_detaile_comment = cxt.getResources().getString(R.string.look_all_comments
                , comment_num);
        dynamic_comment_detail_num_tv.setText(look_detaile_comment);
        //如果没有评论就不显示评论提示信息
        if (comment_num == 0) {
            comment_hint_rl.setVisibility(View.GONE);
        } else {
            comment_hint_rl.setVisibility(View.VISIBLE);
        }
    }


    //将时间戳转化为日期格式
    String formatData(long timeStamp) {
        String result = "";
        if (timeUtil.isToday(timeStamp)) {
            result = today + " " + timeUtil.formatHourAndMin(timeStamp);
        } else {
            result = timeUtil.formatData(timeStamp);
        }
        return result;
    }


    //针对该动态是否点赞了
    void changSupportStatus(int status) {
        if (status == 1) {
            dynamic_support_iv.setBackgroundResource(R.mipmap.supported);
        } else {
            dynamic_support_iv.setBackgroundResource(R.mipmap.dynamic_support);
        }
    }


    //点赞、取消赞时候更新赞列表
    void updateSupportInfo(int status) {
        dynamicListener.isSupport(status, position);
    }


    //图片列表
    void setProPicturesRecyclerView() {
        propicture_list_recyclerview.setItemAnimator(new DefaultItemAnimator());
        propicture_list_recyclerview.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        MyGridLayoutManager layoutManager = new MyGridLayoutManager(cxt, 3);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        propicture_list_recyclerview.setLayoutManager(layoutManager);
        proPicturesItemAdapter.setAdapterData(proPicturesArray);
        proPicturesItemAdapter.setRecycleItemClickListener(itemClicked);
        proPicturesItemAdapter.setParentPostion(position);
        propicture_list_recyclerview.setAdapter(proPicturesItemAdapter);
    }


    //赞列表
    void setSupportRecyclerView() {
        support_list_recyclerview.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        MyLinearLayoutManager layoutManager = new MyLinearLayoutManager(cxt);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        support_list_recyclerview.setLayoutManager(layoutManager);
        supportItemAdapter.setAdapterData(supportArray);
        supportItemAdapter.setRecycleItemClickListener(itemClicked);
        supportItemAdapter.setParentPostion(position);
        support_list_recyclerview.setAdapter(supportItemAdapter);
    }


    //评论列表
    void setCommentRecyclerView() {
        comment_list_recyclerview.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        MyLinearLayoutManager layoutManager = new MyLinearLayoutManager(cxt);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        comment_list_recyclerview.setLayoutManager(layoutManager);
        commentItemAdapter.setAdapterData(commentArray);
        commentItemAdapter.setRecycleItemClickListener(itemClicked);
        commentItemAdapter.setParentPostion(position);
        comment_list_recyclerview.setAdapter(commentItemAdapter);
    }

    //请求点赞
    void requestSupport() {
        momentId = momentBean.getMomentId();
        httpOperator.requestSupport(httpUtil, momentId, requestSupportHandler);
    }

    //请求取消赞
    void requestCancelSupport() {
        momentId = momentBean.getMomentId();
        httpOperator.requestCancelSupport(httpUtil, momentId, requestSupportHandler);
    }


    //获取点赞、取消点赞回调
    AsyncHttpResponseHandler requestSupportHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestSupportHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        is_support = is_support == 1 ? 0 : 1;
                        updateSupportInfo(is_support);
                    } else {
                        httpErro.showDynamicErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);

            LUtil.i(LOG_TAG, "____failure__________" + responseString.toString());
        }
    };


    //取消赞对话框
    void openCancelSupportDialog() {
        new MaterialDialog.Builder(cxt)
                .title(R.string.warm_prompt)
                .titleGravity(GravityEnum.CENTER)
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        LUtil.i(LOG_TAG, "_______确定按钮________");
                        requestCancelSupport();
                    }

                    @Override
                    public void onNegative(MaterialDialog dialog) {
                        LUtil.i(LOG_TAG, "_______取消按钮________");
                    }
                })
                .content(R.string.cancel_support_dialog_content)
                .positiveText(R.string.ok)
                .negativeText(R.string.cancel)
                .show();

    }

    @Click({R.id.dynamic_item_support_iv, R.id.dynamic_item_comment_iv,
            R.id.dynamic_item_one_pic_iv, R.id.dynamic_item_rl
    })
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.dynamic_item_support_iv://点赞
                if (is_support == 1) {
                    requestCancelSupport();
                } else {
                    requestSupport();
                }
                break;
            case R.id.dynamic_item_comment_iv://评论
                itemClicked.onRecyclerItemClicked(Constant.DYNAMIC_ADD_COMMENT_FLAG, position);
                break;
            case R.id.dynamic_item_one_pic_iv:
                itemClicked.onRecyclerItemClicked(Constant.DYNAMIC_PICT_FLAG, 0, position);
                break;
            case R.id.dynamic_item_rl:
                itemClicked.onRecyclerItemClicked(Constant.DYNAMIC_COMMENT_ITEM, position);
                break;
            default:
                break;
        }
    }


    public void setRecyclerItemClick(RecyclerItemClicked clicked) {
        this.itemClicked = clicked;
    }

    public void setDynamicListener(DynamicListener mlistener) {
        this.dynamicListener = mlistener;
    }


}
